import axios from 'axios'

// 创建 axios 实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'If-Modified-Since': new Date().toUTCString()
  }
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    // 可在此处添加全局 loading
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    const { code, message, data } = response.data
    if (code === 200) {
      return data
    } else {
      // 可在此处添加全局错误提示
      console.error(message || '请求失败')
      return Promise.reject(new Error(message || 'Error'))
    }
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // window.location.href = '/login'
          break
        case 403:
          console.error('无权限访问')
          break
        case 404:
          console.error('请求资源不存在')
          break
        case 500:
          console.error('服务器错误')
          break
        default:
          console.error(error.message)
      }
    }
    return Promise.reject(error)
  }
)

// 封装请求方法
export const get = (url: string, params: any) => instance.get(url, { params })
export const post = (url: string, data: any) => instance.post(url, data)

// 默认导出实例
export default instance